<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="/assets/ffmpeg/package/dist/umd/ffmpeg.js"></script>
    <script src="/assets/util/package/dist/umd/index.js"></script>
  </head>

  <body>
    <h3>Select multiple video files to Concatenate</h3>
    <video id="output-video" controls></video><br />
    <input type="file" id="uploader" multiple />
    <p id="message"></p>
    <script>
      const { fetchFile } = FFmpegUtil;
      const { FFmpeg } = FFmpegWASM;
      let ffmpeg = null;

      const transcode = async ({ target: { files } }) => {
        const message = document.getElementById("message");
        if (ffmpeg === null) {
          ffmpeg = new FFmpeg();
          ffmpeg.on("log", ({ message }) => {
            console.log(message);
          })
          ffmpeg.on("progress", ({ progress, time }) => {
	    message.innerHTML = `${time / 1000000} s`;
          });
          await ffmpeg.load({
            coreURL: "/assets/core/package/dist/umd/ffmpeg-core.js",
          });
        }
        message.innerHTML = "Start Concating";
        const inputPaths = [];
        for (const file of files) {
          const { name } = file;
          ffmpeg.writeFile(name, await fetchFile(file));
          inputPaths.push(`file ${name}`);
        }
        await ffmpeg.writeFile('concat_list.txt', inputPaths.join('\n'));
        await ffmpeg.exec(['-f', 'concat', '-safe', '0', '-i', 'concat_list.txt', 'output.mp4']);
        message.innerHTML = "Complete Concating";
        const data = await ffmpeg.readFile('output.mp4');
        const video = document.getElementById("output-video");
        video.src = URL.createObjectURL(
          new Blob([data.buffer], {
            type: "video/mp4"
          })
        );
      };
      const elm = document.getElementById("uploader");
      elm.addEventListener("change", transcode);
    </script>
  </body>
</html>
